package com.sanjiahantang.youjiaclient.module.common.holders;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.MyGridView;
import com.sanjiahantang.uilibrary.views.bannerview.BannerView;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.module.common.adapters.ImageAddAdapter;
import com.sanjiahantang.youjiaclient.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiaclient.module.evaluate.beans.EvaGoodsBean;
import com.sanjiahantang.youjiaclient.module.evaluate.beans.GoodsAppraiseInitResponse;
import com.sanjiahantang.youjiaclient.module.evaluate.views.impl.EVAGoodsListActivity;
import com.sanjiahantang.youjiaclient.module.goods.adapters.GoodsListAdapter;
import com.sanjiahantang.youjiaclient.module.goods.beans.GoodsBean;
import com.sanjiahantang.youjiaclient.module.match.beans.MatchBean;
import com.sanjiahantang.youjiaclient.umengshare.UmengShareManager;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import q.rorbin.badgeview.QBadgeView;


/**
 * Created by zy on 2017/10/18.
 */

public class CommonHolder extends RecyclerView.ViewHolder implements StaticValue {
    private View itemView;

    public CommonHolder(Activity activity, View itemView, int viewType, Object data) {
        super(itemView);
        this.itemView = itemView;
        bindData(activity, viewType, data);
    }

    public void bindData(Activity activity, int viewType, Object data) {
        switch (viewType) {
            case HOLDER_TYPE_GOODS_BANNER:
                initGoodsBanner(activity, itemView, data);
                break;
            case HOLDER_TYPE_GOODS_DETAIL:
                initGoodsDetail(itemView, (Object[]) data);
                break;
            case HOLDER_TYPE_MATCH_HEADER:
                initMatchHeader(activity, itemView, (String) data);
                break;
            case HOLDER_TYPE_GOODS_WEBVIEW:
                initWeb(itemView, (String) data);
                break;
            case HOLDER_TYPE_GOODS_RECOMMEND:
                initRecommend(activity, itemView, (List<MatchBean.Goods>) data);
                break;
            case HOLDER_TYPE_GOODS_RECOMMEND_MORE:
                initRecommendMore(activity, itemView, (List<MatchBean.Goods>) data);
                break;
            case HOLDER_TYPE_MATCH_RECOMMEND:
                initRecommend(activity, itemView, (List<MatchBean.Goods>) data, 1);
                break;
            case HOLDER_TYPE_GOODS_COMMENTS:
                initGoodsComments(activity, itemView, (List<EvaGoodsBean.Item>) data);
                break;
            case HOLDER_TYPE_EVALUATE_GOODS:
                initEvaluateGoods(activity, itemView, (Object[]) data);
                break;
            default:
                defaultView();
                break;
        }
    }


    //商品评价
    private void initEvaluateGoods(Activity activity, View itemView, Object[] param) {
        GoodsAppraiseInitResponse.Data data = (GoodsAppraiseInitResponse.Data) param[0];
        BaseView.OnLoadListener listener = (BaseView.OnLoadListener) param[1];
        TextView txtGoodsName = (TextView) itemView.findViewById(R.id.txtGoodsName);
        ImageView ivGoodsImage = (ImageView) itemView.findViewById(R.id.ivGoodsImage);
        txtGoodsName.setText(data.getGoodsName());
        Picasso.with(activity).load(FileUtils.rePath(data.getUrl())).into(ivGoodsImage);

        MyGridView gvGoodsEvaluate = (MyGridView) itemView.findViewById(R.id.gvGoodsEvaluate);
        gvGoodsEvaluate.setAdapter(new ImageAddAdapter(activity, param));
    }

    private void defaultView() {

    }

    private void initGoodsComments(final Activity activity, View itemView, final List<EvaGoodsBean.Item> data) {
        TextView txtCommentCount = (TextView) itemView.findViewById(R.id.txtCommentCount);
        txtCommentCount.setText(String.valueOf(data == null ? 0 : data.size()));
        if (data == null || data.size() == 0) {
            itemView.findViewById(R.id.itemComment).setVisibility(View.GONE);
            itemView.findViewById(R.id.txtCommentMore).setVisibility(View.GONE);
            return;
        }
        TextView txtPhone = (TextView) itemView.findViewById(R.id.txtPhone);
        txtPhone.setText(data.get(0).getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));

        TextView txtCreateTime = (TextView) itemView.findViewById(R.id.txtCreateTime);
        if (data != null && data.get(0) != null && data.get(0).getCreateTime() != null) {
            txtCreateTime.setText(data.get(0).getCreateTime().substring(0, "yyyy-MM-dd".length()));
        }

        TextView txtContent = (TextView) itemView.findViewById(R.id.txtContent);
        txtContent.setText(data.get(0).getPlace());


        TextView txtAttr = (TextView) itemView.findViewById(R.id.txtAttr);

        if (data.get(0).getGoodsPropertyName() != null)
            txtAttr.setText(data.get(0).getGoodsPropertyName().replace(",", " "));

        RatingBar ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
        ratingBar.setRating(Integer.parseInt(data.get(0).getNumber()));
        ratingBar.setIsIndicator(true);
        GridView gvImageList = (GridView) itemView.findViewById(R.id.gvImageList);
        if (data.get(0).getImgUrlList() == null || data.get(0).getImgUrlList().size() == 0) {
            gvImageList.setVisibility(View.GONE);
        } else {
            gvImageList.setVisibility(View.VISIBLE);
            gvImageList.setAdapter(new com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter<GoodsBean.Image>(activity, R.layout.item_image, data.get(0).getImgUrlList()) {
                @Override
                protected void convert(com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper helper, final GoodsBean.Image item) {
                    ImageView iv = helper.getView(R.id.image);
                    Picasso.with(context).load(FileUtils.rePath(item.getUrl())).placeholder(R.drawable.i_rect_bg).into(iv);
                    helper.getView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Utils.showPicDialog((Activity) context,FileUtils.rePath(item.getUrl()),R.drawable.i_rect_bg);
                        }
                    });
                }
            });
        }
        if (data.size() > 1) {
            itemView.findViewById(R.id.txtCommentMore).setVisibility(View.VISIBLE);
            itemView.findViewById(R.id.txtCommentMore).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Bundle b = new Bundle();
                    b.putSerializable("list", (ArrayList<EvaGoodsBean.Item>) data);
                    Intent intent = new Intent(activity, EVAGoodsListActivity.class);
                    intent.putExtra(KEY_PARAM, b);
                    activity.startActivity(intent);
                }
            });
        } else {
            itemView.findViewById(R.id.txtCommentMore).setVisibility(View.GONE);
        }
    }

    private void initMatchHeader(final Context context, View itemView, String url) {
        ImageView ivHeader = (ImageView) itemView.findViewById(R.id.ivHeader);
        Picasso.with(context).load(FileUtils.rePath(url)).placeholder(R.drawable.i_match).into(ivHeader);
        itemView.findViewById(R.id.rlBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Activity) context).finish();
            }
        });
        itemView.findViewById(R.id.rlCart).setVisibility(View.GONE);
        itemView.findViewById(R.id.rlCart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UmengShareManager.share((Activity) context, "");
            }
        });
    }

    private void initGoodsBanner(final Activity activity, View itemView, Object obj) {
        Object[] param = (Object[]) obj;
        final List<GoodsBean.Image> data = (List<GoodsBean.Image>) param[0];
        View.OnClickListener listener = (View.OnClickListener) param[1];
        int num = (int) param[2];

        if (data == null) {
            return;
        }
        BannerView bv = (BannerView) ((RelativeLayout) itemView).getChildAt(0);
        List<HashMap<String, Object>> imgList = new ArrayList<>();
        for (int i = 0, max = data.size(); i < max; i++) {

            HashMap<String, Object> map = new HashMap<>();
            map.put("img", FileUtils.rePath(data.get(i).getUrl()));
            map.put("action", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });
            imgList.add(map);
        }
        bv.initAdapterData(imgList);
        bv.setDrawerMode(BannerView.STYLE_Dot);
        bv.setLocationMode(BannerView.MODE_CENTER);
        itemView.findViewById(R.id.rlBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });
        View rlCart = itemView.findViewById(R.id.rlCart);
        if (param[3] != null) {
            rlCart.setVisibility(View.GONE);
        }
        rlCart.setOnClickListener(listener);

        QBadgeView messageQbv = new QBadgeView(activity);
        messageQbv.bindTarget(itemView.findViewById(R.id.rlCart)).setBadgeGravity(Gravity.TOP | Gravity.END);
        messageQbv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                ConfigValue.hasRegisterReceiver = false;
                intent.putExtra(KEY_PAGE, 3);
                activity.startActivity(intent);
            }
        });
        if (num > 0) {
            messageQbv.setBadgeNumber(num)
                    .setGravityOffset(10, -2, true)
                    .setBadgeTextSize(8, true);
        } else {
            messageQbv.setBadgeText(String.valueOf(num))
                    .setGravityOffset(2, 2, true)
                    .setBadgeTextSize(8, true)
                    .hide(false);
        }

    }

    private void initGoodsDetail(View itemView,Object[] param ) {
        GoodsBean.Data data = (GoodsBean.Data) param[0];
        TextView txtOldPrice = (TextView) itemView.findViewById(R.id.txtOldPrice);
        TextView txtGoodsName = (TextView) itemView.findViewById(R.id.txtGoodsName);
        txtGoodsName.setText(data.getGoodsName());
        TextView txtPrice = (TextView) itemView.findViewById(R.id.txtPrice);

        TextView txtSoldCount = (TextView) itemView.findViewById(R.id.txtSoldCount);
        txtSoldCount.setText(String.valueOf(data.getSoldCount()));
        String unit = data.getUnit();
        if (TextUtils.isEmpty(unit)){
            unit = "";
        }else if (TextUtils.equals("元",unit)){
            unit = "";
        }else if (!unit.contains("元")){
            unit = String.format("元/%s",unit);
        }
        if (data.getIsSale() == 1) {
            txtPrice.setText(String.format("%.2f %s",data.getSalePrice(), unit));
            txtOldPrice.setText(String.format("%.2f %s",data.getBasePrice(), unit));
            txtOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            itemView.findViewById(R.id.txtIsSale).setVisibility(View.VISIBLE);
        } else {
            txtPrice.setText(String.format("%.2f %s",data.getBasePrice(), unit));
            txtOldPrice.setVisibility(View.GONE);
            itemView.findViewById(R.id.txtIsSale).setVisibility(View.GONE);
        }

        itemView.findViewById(R.id.btnParam).setOnClickListener((View.OnClickListener) param[1]);
    }

    private void initWeb(View itemView, String data) {
        if (data == null) {
            return;
        }
        WebView wvGoods = (WebView) itemView;
        WebSettings mSetting = wvGoods.getSettings();
        mSetting.setJavaScriptEnabled(true);
        mSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wvGoods.setWebChromeClient(new WebChromeClient());
        wvGoods.setWebViewClient(new WebViewClient() {
        });
        mSetting.setJavaScriptEnabled(true);//启用js
        mSetting.setBlockNetworkImage(false);//解决图片不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            mSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        if (data.indexOf("http") == 0) {
            wvGoods.loadUrl(data);
        } else {
            String css = "<style>img{width:100%;}body{word-wrap:break-word;}</style>";
            data = css + data;
            wvGoods.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
        }
    }

    private void initRecommend(Activity activity, View itemView, List<MatchBean.Goods> data, int type) {
        if (type > 0) {
            itemView.findViewById(R.id.rlHeader).setVisibility(View.GONE);
            itemView.setBackgroundColor(Color.WHITE);
        } else {
            itemView.setBackgroundColor(Color.rgb(0xf8, 0xf8, 0xf8));
        }




        String typegoods = (String) itemView.getTag(R.id.decode);
        MyGridView gvGoodsRecommend = (MyGridView) itemView.findViewById(R.id.gvGoodsRecommend);
        GoodsListAdapter gvadapter = (GoodsListAdapter) gvGoodsRecommend.getAdapter();
        if (gvadapter == null || type == -1){
            gvadapter = new GoodsListAdapter(activity, data, type);
        } else {
            gvadapter.addAll(data);
        }

        if (typegoods != null) {
            gvadapter.setGoodsType(typegoods);
        }
        gvGoodsRecommend.setAdapter(gvadapter);

    }

    private void initRecommend(Activity activity, View itemView, List<MatchBean.Goods> data) {
        initRecommend(activity, itemView, data, -1);
    }

    private void initRecommendMore(Activity activity, View itemView, List<MatchBean.Goods> data) {
        initRecommend(activity, itemView, data, 0);
    }
}
